<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>
    <style>
        :root {
            --primary-color: #fe7618;
            --primary-hover: #e6661a;
            --danger-color: #dc3545;
            --danger-hover: #c82333;
            --light-gray: #f8f9fa;
            --gray: #e9ecef;
            --dark-gray: #6c757d;
            --text-color: #343a40;
            --white: #fff;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: var(--light-gray);
            color: var(--text-color);
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Header */
        .header {
            background: var(--white);
            padding: 15px 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            height: 45px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 20px;
            font-weight: 500;
        }
        
        .btn {
            border: none;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s;
            font-size: 14px;
        }

        .btn-danger {
            background: var(--danger-color);
            color: var(--white);
        }
        .btn-danger:hover {
            background: var(--danger-hover);
        }

        .btn-secondary {
            background: var(--white);
            color: var(--text-color);
            border: 1px solid var(--gray);
        }
        .btn-secondary:hover {
            background: var(--light-gray);
            border-color: #ced4da;
        }
        
        /* Login Section */
        .login-section {
            background: var(--white);
            padding: 50px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            max-width: 450px;
            margin: 80px auto;
        }
        
        .login-section h2 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 1.8em;
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        .form-group input {
            width: 100%;
            padding: 14px;
            border: 1px solid var(--gray);
            border-radius: var(--border-radius);
            font-size: 16px;
            transition: all 0.2s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(254, 118, 24, 0.2);
        }
        
        .login-btn {
            width: 100%;
            padding: 14px;
            background: var(--primary-color);
            color: var(--white);
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .login-btn:hover {
            background: var(--primary-hover);
        }
        
        /* Stats Section */
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: var(--white);
            padding: 25px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .stat-number {
            font-size: 2.5em;
            font-weight: 700;
            color: var(--primary-color);
        }
        
        .stat-label {
            color: var(--dark-gray);
            font-size: 1.1em;
            margin-top: 8px;
        }
        
        /* Admin Panel (Table Section) */
        .admin-panel {
            background: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }
        
        .panel-header {
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--gray);
        }
        
        .panel-header h2 {
            margin: 0;
            font-size: 1.5em;
        }
        
        .panel-header button {
            background: var(--primary-color);
            color: var(--white);
            border: none;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .panel-header button:hover {
            background: var(--primary-hover);
        }
        
        .table-container {
            padding: 10px 30px 30px;
            max-height: 65vh;
            overflow-y: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid var(--gray);
        }
        
        th {
            background: var(--light-gray);
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 1;
        }
        
        tr:last-child td {
            border-bottom: none;
        }
        
        tr:hover {
            background: #f1f3f5;
        }
        
        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            padding: 20px 30px;
            border-top: 1px solid var(--gray);
        }
        
        .pagination button {
            padding: 8px 16px;
            border: 1px solid var(--gray);
            background: var(--white);
            cursor: pointer;
            border-radius: var(--border-radius);
            transition: all 0.2s;
        }
        
        .pagination button:hover {
            background: var(--gray);
        }
        
        .pagination button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .pagination #pageInfo {
            font-weight: 500;
        }
        
        /* Utility Classes */
        .hidden {
            display: none !important;
        }
        
        .message {
            padding: 12px;
            margin-top: 20px;
            border-radius: var(--border-radius);
            text-align: center;
            font-weight: 500;
        }
        
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            font-size: 1.2em;
            color: var(--dark-gray);
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .header {
                flex-direction: column;
                gap: 15px;
                padding: 20px;
            }
            
            .login-section {
                padding: 30px;
                margin: 40px auto;
            }

            .stats {
                grid-template-columns: 1fr 1fr;
                gap: 15px;
            }

            .table-container {
                overflow-x: auto;
            }
            
            table {
                min-width: 700px;
            }

            .pagination {
                padding: 15px 10px;
                gap: 5px;
            }

            .pagination #pageInfo {
                font-size: 12px;
            }

            .pagination button {
                padding: 8px 12px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 登录区域 -->
        <div id="loginSection" class="login-section">
            <img class="logo" src="/static/img/logo.png" alt="Logo" style="display: block; margin: 0 auto 20px;">
            <h2>管理员登录</h2>
            <form id="loginForm">
                <div class="form-group">
                    <label for="username">用户名：</label>
                    <input type="text" id="username" name="username" placeholder="请输入管理员用户名" required>
                </div>
                <div class="form-group">
                    <label for="password">密码：</label>
                    <input type="password" id="password" name="password" placeholder="请输入密码" required>
                </div>
                <button type="submit" class="login-btn">登录</button>
            </form>
            <div id="loginMessage"></div>
        </div>

        <!-- 管理面板 -->
        <div id="adminPanel" class="hidden">
            <!-- 头部 -->
            <div class="header">
                <img class="logo" src="/static/img/logo.png" alt="Logo">
                <div class="user-info">
                    <span>欢迎，<span id="adminUsername"></span></span>
                    <button id="toggleChangePasswordBtn" class="btn btn-secondary">修改密码</button>
                    <button class="btn btn-danger" onclick="logout()">退出登录</button>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div class="stats">
                <div class="stat-card">
                    <div class="stat-number" id="totalForms">0</div>
                    <div class="stat-label">总提交数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="todayForms">0</div>
                    <div class="stat-label">今日提交</div>
                </div>
            </div>

            <!-- 修改密码卡片 -->
            <div id="changePasswordSection" class="admin-panel hidden" style="margin-bottom: 30px;">
                <div class="panel-header">
                    <h2>修改密码</h2>
                </div>
                <form id="changePasswordForm" style="padding: 30px;">
                    <div class="form-group">
                        <label for="old_password">当前密码：</label>
                        <input type="password" id="old_password" name="old_password" placeholder="请输入当前使用的密码" required>
                    </div>
                    <div class="form-group">
                        <label for="new_password">新密码：</label>
                        <input type="password" id="new_password" name="new_password" placeholder="请输入新密码（至少6位）" required>
                    </div>
                    <div class="form-group">
                        <label for="confirm_password">确认新密码：</label>
                        <input type="password" id="confirm_password" name="confirm_password" placeholder="请再次输入新密码" required>
                    </div>
                    <button type="submit" class="login-btn">确认修改密码</button>
                    <div id="changePasswordMessage" style="margin-top: 20px;"></div>
                </form>
            </div>

            <!-- 表单列表 -->
            <div class="admin-panel">
                <div class="panel-header">
                    <h2>学生表单提交记录</h2>
                    <button onclick="loadForms()" style="background: rgba(255,255,255,0.2); border: 1px solid white; color: white; padding: 8px 16px; border-radius: 5px; cursor: pointer;">刷新数据</button>
                </div>
                
                <div class="table-container">
                    <div id="formsLoading" class="loading">加载中...</div>
                    <table id="formsTable" class="hidden">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>姓名</th>
                                <th>手机号</th>
                                <th>年级</th>
                                <th>年龄</th>
                                <th>提交时间</th>
                            </tr>
                        </thead>
                        <tbody id="formsTableBody">
                        </tbody>
                    </table>
                </div>
                
                <div id="pagination" class="pagination hidden">
                    <button id="prevBtn" onclick="changePage(-1)">上一页</button>
                    <span id="pageInfo">第 1 页，共 1 页</span>
                    <button id="nextBtn" onclick="changePage(1)">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api';
        let currentPage = 1;
        let totalPages = 1;

        // 页面加载时检查登录状态
        window.addEventListener('load', () => {
            checkLoginStatus();

            // 切换修改密码表单的显示
            document.getElementById('toggleChangePasswordBtn').addEventListener('click', () => {
                const section = document.getElementById('changePasswordSection');
                section.classList.toggle('hidden');
            });
        });

        // 修改密码表单提交
        document.getElementById('changePasswordForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const old_password = document.getElementById('old_password').value;
            const new_password = document.getElementById('new_password').value;
            const confirm_password = document.getElementById('confirm_password').value;
            const messageDiv = document.getElementById('changePasswordMessage');
            const submitButton = e.target.querySelector('button');
            
            messageDiv.innerHTML = '';
            submitButton.disabled = true;
            submitButton.textContent = '修改中...';

            if (new_password !== confirm_password) {
                messageDiv.innerHTML = `<div class="message error">新密码和确认密码不匹配</div>`;
                submitButton.disabled = false;
                submitButton.textContent = '确认修改密码';
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/admin/change-password`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({ old_password, new_password, confirm_password })
                });

                const result = await response.json();

                if (result.success) {
                    messageDiv.innerHTML = `<div class="message success">${result.message}</div>`;
                    setTimeout(() => {
                        logout();
                    }, 2000);
                } else {
                    messageDiv.innerHTML = `<div class="message error">${result.message}</div>`;
                    submitButton.disabled = false;
                    submitButton.textContent = '确认修改密码';
                }
            } catch (error) {
                messageDiv.innerHTML = `<div class="message error">网络错误，请稍后重试</div>`;
                submitButton.disabled = false;
                submitButton.textContent = '确认修改密码';
            }
        });

        async function checkLoginStatus() {
            try {
                const response = await fetch(`${API_BASE}/admin/status`, {
                    credentials: 'include'
                });
                const result = await response.json();
                
                if (result.success && result.data.logged_in) {
                    document.getElementById('adminUsername').textContent = result.data.username;
                    showAdminPanel();
                    loadForms();
                } else {
                    showLoginSection();
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                showLoginSection();
            }
        }

        // 管理员登录
        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const loginData = {
                username: document.getElementById('username').value.trim(),
                password: document.getElementById('password').value
            };

            try {
                const response = await fetch(`${API_BASE}/admin/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'include',
                    body: JSON.stringify(loginData)
                });

                const result = await response.json();
                const messageDiv = document.getElementById('loginMessage');

                if (result.success) {
                    messageDiv.innerHTML = `<div class="message success">${result.message}</div>`;
                    document.getElementById('adminUsername').textContent = result.data.username;
                    setTimeout(() => {
                        showAdminPanel();
                        loadForms();
                    }, 1000);
                } else {
                    messageDiv.innerHTML = `<div class="message error">${result.message}</div>`;
                }
            } catch (error) {
                document.getElementById('loginMessage').innerHTML = 
                    `<div class="message error">网络错误，请检查服务器是否启动</div>`;
            }
        });

        // 加载表单数据
        async function loadForms(page = 1) {
            try {
                document.getElementById('formsLoading').classList.remove('hidden');
                document.getElementById('formsTable').classList.add('hidden');
                
                const response = await fetch(`${API_BASE}/admin/forms?page=${page}&per_page=10`, {
                    credentials: 'include'
                });

                const result = await response.json();

                if (result.success) {
                    const forms = result.data.forms;
                    const pagination = result.data.pagination;
                    
                    // 更新统计数据
                    document.getElementById('totalForms').textContent = pagination.total;
                    
                    // 计算今日提交数
                    const today = new Date().toISOString().split('T')[0];
                    const todayCount = forms.filter(form => 
                        form.created_at.startsWith(today)
                    ).length;
                    document.getElementById('todayForms').textContent = todayCount;
                    
                    // 更新表格
                    updateFormsTable(forms);
                    
                    // 更新分页
                    currentPage = pagination.page;
                    totalPages = pagination.pages;
                    updatePagination(pagination);
                    
                    document.getElementById('formsLoading').classList.add('hidden');
                    document.getElementById('formsTable').classList.remove('hidden');
                    document.getElementById('pagination').classList.remove('hidden');
                } else {
                    if (result.message === '请先登录') {
                        showLoginSection();
                    } else {
                        alert('加载失败: ' + result.message);
                    }
                }
            } catch (error) {
                console.error('加载表单数据失败:', error);
                alert('网络错误，请检查服务器连接');
            }
        }

        // 更新表格内容
        function updateFormsTable(forms) {
            const tbody = document.getElementById('formsTableBody');
            tbody.innerHTML = '';
            
            forms.forEach(form => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${form.id}</td>
                    <td>${form.name}</td>
                    <td>${form.phone}</td>
                    <td>${form.grade}年级</td>
                    <td>${form.age}岁</td>
                    <td>${form.created_at}</td>
                `;
            });
        }

        // 更新分页信息
        function updatePagination(pagination) {
            document.getElementById('pageInfo').textContent = 
                `第 ${pagination.page} 页，共 ${pagination.pages} 页 (总计 ${pagination.total} 条记录)`;
            
            document.getElementById('prevBtn').disabled = !pagination.has_prev;
            document.getElementById('nextBtn').disabled = !pagination.has_next;
        }

        // 翻页
        function changePage(direction) {
            const newPage = currentPage + direction;
            if (newPage >= 1 && newPage <= totalPages) {
                loadForms(newPage);
            }
        }

        // 登出
        async function logout() {
            try {
                const response = await fetch(`${API_BASE}/admin/logout`, {
                    method: 'POST',
                    credentials: 'include'
                });
                
                const result = await response.json();
                if (result.success) {
                    showLoginSection();
                }
            } catch (error) {
                console.error('登出失败:', error);
            }
        }

        // 显示登录界面
        function showLoginSection() {
            document.getElementById('loginSection').classList.remove('hidden');
            document.getElementById('adminPanel').classList.add('hidden');
            document.getElementById('loginForm').reset();
            document.getElementById('loginMessage').innerHTML = '';
        }

        // 显示管理面板
        function showAdminPanel() {
            document.getElementById('loginSection').classList.add('hidden');
            document.getElementById('adminPanel').classList.remove('hidden');
        }
    </script>
</body>
</html>